// index.js
// 获取应用实例
const app = getApp()

const dataList = {
  // 规格
  "spu_spec_all_values": [
    {
      "name": "尺寸",
      "values": [
        "S", "M"
      ]
    },
    {
      "name": "颜色",
      "values": [
        "白色", "黄色"
      ]
    }
  ],
  // 选中规格
  "specification": [
    {
      "key": "尺寸",
      "val": "S"
    },
    {
      "key": "颜色",
      "val": "白色"
    }
  ],
  // 单品
  "sku_setting_specs": [
    {
      "sku_id": "1",
      "pid": '1a',
      "sepcs": {
        "尺寸": "S",
        "颜色": "白色"
      },
      "image": "../image/white.png",
      "stock": 3,
      "show_price": 1999
    },
    {
      "sku_id": "2",
      "sepcs": {
        "尺寸": "M",
        "颜色": "白色"
      },
      "image": "../image/white.png",
      "stock": 3,
      "show_price": 1999
    },
    {
      "sku_id": "3",
      "sepcs": {
        "尺寸": "S",
        "颜色": "黄色"
      },
      "image": "../image/yellow.png",
      "stock": 3,
      "show_price": 2000
    },
    {
      "sku_id": "4",
      "sepcs": {
        "尺寸": "M",
        "颜色": "黄色"
      },
      "image": "../image/yellow.png",
      "stock": 0,
      "show_price": 2000
    }
  ]
}

Page({
  data: {
    dataList: dataList,
    allValues: [],
    skuStock: 0, // 库存
    skuImage : '', // sku图片
    skuShowPrice: '', // 现在sku的价格
    activeSizeValue: [], // 已选的规格
    // motto: 'Hello World',
    // userInfo: {},
    // hasUserInfo: false,
    // canIUse: wx.canIUse('button.open-type.getUserInfo'),
    // canIUseGetUserProfile: false,
    // canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl') && wx.canIUse('open-data.type.userNickName') // 如需尝试获取用户信息可改为false
  },
  // 事件处理函数
  bindViewTap() {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  onLoad() {
    // if (wx.getUserProfile) {
    //   this.setData({
    //     canIUseGetUserProfile: true
    //   })
    // }
    const activeSizeValue = this.formatSpecification(dataList.specification)
    const allValues = this.formatAllValues(dataList.spu_spec_all_values)
    this.setCurrentInfo(activeSizeValue)
    console.log(allValues)
    this.setData({ activeSizeValue, allValues })
  },
  formatSpecification (specification) {
    if (Array.isArray(specification)) {
      return specification.map(i => `${i.key}:${i.val}`)
    }
    return []
  },
  formatAllValues (values) {
    const result = values.map(item => {
      const values = item.values.map(cur => ({ key: item.name, value: cur, disable: false }))
      return { ...item, values }
    })
    return result
  },
  setCurrentInfo (activeSizeValue) {
    if (Array.isArray(activeSizeValue)) {
      const target = dataList.sku_setting_specs.find(item => {
        const hasVal = Object.keys(item.sepcs).every(key => {
          return activeSizeValue.find(cur => cur === `${key}:${item.sepcs[key]}`)
        })
        return hasVal
      })
      this.setData({
        skuStock: target.stock,
        skuImage : target.image,
        skuShowPrice: target.show_price
      })
      return target
    }
  },
  handleClick (event) {
    const dataset = event.currentTarget.dataset
    if (dataset.able) return
    const target = this.formatSpecification([dataset])
    const current = this.data.activeSizeValue.slice()
    current[dataset.idx] = target[0]
    this.setCurrentInfo(current)
    this.setData({ activeSizeValue: current })
    this.getChildren(dataset.val)
  },
  getChildren (skey) {
    console.log(skey)
    // 全排列组合
    const list = dataList.spu_spec_all_values.map(item => item.values)
    const res = list.reduce((a, b) => {
      return a.flatMap(x => b.map(y => [...x, y]))
    }, [[]])
    // 选中的组合
    const result = []
    res.forEach(item => {
      if (item.includes(skey)) {
        result.push(item)
      }
    })
    // console.log(result)
    const disableList = []
    // 去查库存为零的商品
    result.forEach(item => {
      const tar = dataList.sku_setting_specs.find(cur => {
        const sepcs = Object.values(cur.sepcs)
        const isVal = item.every(k => sepcs.includes(k))
        return isVal
      })
      if (tar.stock === 0) {
        disableList.push(tar)
      }
    })
    // 给商品添加禁用
    let allValues = this.formatAllValues(dataList.spu_spec_all_values)
    disableList.forEach(item => {
      Object.keys(item.sepcs).forEach(key => {
        // { 尺寸: "M", 颜色: "黄色" }
        console.log(key)
        allValues.forEach(cur => {
          const tar = cur.values.find(tar => {
            return tar.key === key && tar.value === item.sepcs[key]
          })
          if (tar) {
            tar.disable = tar.value !== skey
          }
          console.log(tar)
        })
      })
    })
    this.setData({ allValues })
  }
})
